<?php

class Page extends A_Content {
	
	
	/**
	 * Returns instance of SinglePage class
	 *
	 * @param Integer $page_id
	 * @return SinglePage 
	 */
	public function getById($page_id)
	{
		if (!isset($this->_cashe_obj[$page_id])) {
			$this->_cashe_obj[$page_id] = new SinglePage($this->_top,$this,$page_id);
		}
		
		return $this->_cashe_obj[$page_id];
	}
	
	public function add()
	{
		$this->_top->_sql->exeDummy("INSERT INTO ".TAB_PREF."page (permissions) VALUES (0)");
		$page_id = $this->_top->_sql->last_insert_id();
		return $this->getById($page_id);
	}
	

}   

class SinglePage extends A_SingleContent {
	
	#
	# Список переменных меню объявленных для совместимости с Zend Studio
	#
	
	private 
		$_properties_id = array(),
		$_properties_values = array();

	/**
	 * Returns pointer to PageTemplate 
	 *
	 * @var PageTemplate
	 */
	public $template;
		
	protected function loader() {
		unset($this->template);
		
		$page_data = $this->_top->_sql->exe("SELECT * FROM ".TAB_PREF."page WHERE page_id={$this->_content_id}");
		if (count($page_data)==0) return false;
		else $this->_data = $page_data[0];
		
		/*$get_props = $this->_top->_sql->exe("SELECT * FROM ".TAB_PREF."page_property WHERE page_id={$this->_content_id}");
		for ($p=0;$p<count($get_props);$p++) {
			$this->_properties_id[$get_props[$p]["key_name"]] = $get_props[$p]["property_id"];
			$this->_properties_id[$get_props[$p]["key_name"]] = $get_props[$p]["value"];
		}*/
		
		
		$content_list = $this->_top->_sql->exe("SELECT page2content_id,key_name FROM ".TAB_PREF."page2content WHERE page_id={$this->_content_id}");
		$this->_data['content'] = array();
		$this->_data['content_idx'] = array();
		for ($c=0;$c<count($content_list);$c++) {
			$new_content = new PageContent($this->_top,$this,$content_list[$c]['page2content_id']);
			array_push($this->_data['content'],$new_content);
			$this->_data['content_idx'][$new_content->key_name] = $new_content;

		}
		return true;
	}
	
	public function __get($param)
	{
		if ($param=="length") return $this->length();
		elseif ($param=="item") return $this->_data['content'];
		elseif ($param=="template") return $this->getTemplate();
		elseif (isset($this->_data[$param])) return $this->_data[$param];
		elseif (isset($this->_data['content_idx'][$param])) return $this->_data['content_idx'][$param];
/*		elseif (isset($this->_properties_values[$param])) return $this->_properties_values[$param];*/
		else {
			throw $this->_top->Utils->PushError('Geting Undefinded Page object property. Property: '.$param,'Системная ошибка. Обратитесь к разработчикам');
		}
	}
	
	
	public function __set($param,$value)
	{
		if ($param=="content" || $param=="content_idx" || $param=="template_name") {
			return false;
		} elseif ($param=="template") {
			$this->_top->_sql->exeDummy("UPDATE ".TAB_PREF."page SET template_name='$value' WHERE page_id={$this->_content_id}");
			$this->_data['template_name'] = $value;
			
			# Удаляем контнет
			for ($c=0;$c<$this->length();$c++) {
				$this->item($c)->delete();
			}
			
			# Привязываем новый контент
			$contetn_list = $this->template->getContentList();
			
			
			for ($c=0;$c<count($contetn_list);$c++) {
				if (isset($contetn_list[$c]['id'])) {
					$stnd_content = $this->_top->Template->getStndContent($contetn_list[$c]['id']);
					$this->link($stnd_content['id'],$stnd_content['type'],$contetn_list[$c]['key_name']);
				} elseif (isset($contetn_list[$c]['type'])) {
					$new_page_content = $this->add($contetn_list[$c]['type'],$contetn_list[$c]['key_name']);
					$new_page_content->data->applyXML($contetn_list[$c]['xml']);
				} else {
					$this->_top->Utils->PushError('Template config error. Params "Type" or "Id" must be defined in content section declatation', 'Системная ошибка, обратиесь к разработчикам');
				}
				
			}
			
			
			# Переопределяем конструктор
			$this->loader();
			
		} elseif  (isset($this->_data[$param])) {
			
			
			$value = $this->_top->Utils->prepareValueForSQL($value);
			$this->_top->_sql->exeDummy("UPDATE ".TAB_PREF."page SET $param='$value' WHERE page_id={$this->_content_id}");
			$this->_data[$param] = $value;
			return true;
		} /*elseif (isset($this->_properties_id[$param])) {
			$this->_properties_values[$param] = $value;
			$value = $this->_top->Utils->prepareValueForSQL($value);
			$this->_top->_sql->exeDummy("UPDATE ".TAB_PREF."page_property SET value='$value' WHERE property_id={$this->_properties_id[$param]}");
			return true;
		}*/ else {
			return false;
		}
	}
	
	protected function deleter()
	{
		$this->_top->_sql->exeDummy("DELETE FROM ".TAB_PREF."page WHERE page_id={$this->_content_id}");
		for ($l=0;$l<$this->length();$l++) {
			$this->item($l)->delete();
		}
	}
	
	/**
	 * Returns pointer to connection class PageContent
	 *
	 * @param Integer $idx
	 * @return PageContent
	 */
	public function item($idx)
	{
		return $this->_data['content'][$idx];
	}
	
	public function length()
	{
		return count($this->_data['content']);
	}
	
	/**
	 * Возвращает ссылку на контентную единицу привязанную к странице
	 *
	 * @param String $key_name
	 * @return PageContent
	 */
	public function getContent($key_name) {
		return !isset($this->_data['content_idx'][$key_name]) ? false : $this->_data['content_idx'][$key_name];
	}
	
	
	/**
	 * Adds Content on Page
	 *
	 * @param String $content_type
	 * @param String $key_name
	 * @return PageContent
	 */
	public function add($content_type,$key_name)
	{
		$newContent =& $this->_top->Content($content_type)->add();
		if (!$newContent) throw $this->_top->Utils->PushError("Unable to create new content item. Type: $content_type","Невозможно создание нового элемента контента");
		return $this->link($newContent->_content_id,$content_type,$key_name);
	}
	
	/**
	 * Links Content to Page
	 *
	 * @param Integer $content_id
	 * @param String $content_type
	 * @param String $key_name
	 * @return PageContent
	 */
	public function link($content_id,$content_type,$key_name) {
		$content_type = $this->_top->Utils->prepareValueForSQL($content_type);
		$key_name = $this->_top->Utils->prepareValueForSQL($key_name);
		$this->_top->_sql->exeDummy("INSERT INTO ".TAB_PREF."page2content (page_id,content_id,content_type,key_name) 
			VALUES ({$this->page_id},'$content_id','$content_type','$key_name')");
		$page2content_id = $this->_top->_sql->last_insert_id();
		
		$pageContent = new PageContent($this->_top,$this,$page2content_id);
		array_push($this->_data['content'],$pageContent);
		$this->_data['content_idx'][$key_name] = $pageContent;
		
		
		return $pageContent;
	}
	
	
	/**
	 * Return pointer to page template
	 * @return PageTemplate
	 */
	public function getTemplate() {
		return PageTemplate::getInstance($this->template_name);
	}
	
	public function setTemplate($template_name) {
		$this->template = $template_name;
		return true;
	}
	
}

class PageContent extends A_SingleContent {

	private 
		$_content_data;
	
	/**
	 * Return pointer to content object
	 *
	 * @var A_SingleContent
	 */
	public  $data;
		
	protected function loader()
	{
		unset($this->data);
		
		$get_data = $this->_top->_sql->exe("SELECT * FROM ".TAB_PREF."page2content WHERE page2content_id={$this->_content_id}");
		if (count($get_data)==0) return false;
		$this->_data = $get_data[0];
		$this->_content_data = $this->_top->Content($this->_data['content_type'])->getById($this->_data['content_id']);
	}
	
	public function __get($param)
	{
		if ($param=="data") return $this->_content_data;
		elseif (!isset($this->_data[$param])) return false;
		else return $this->_data[$param];
	}
	
	public function __set($param,$value)
	{
		/*$content_data_propery = $this->_content_data!==false ? $this->_content_data->$param : false;
		if ($content_data_propery!==false) $this->_content_data->$param = $value;
		else*/if ($param=="page_id") return false;
		elseif ($param=="content_id") return false;
		elseif ($param=="content_type") return false;
		else $this->update($param,$value);
		return true;
	}
	
	protected function deleter()
	{
	
		if (!in_array(array('type' => $this->content_type, 'id' => $this->content_id),$this->_top->Template->stnd_content)) {
			$this->_content_data->delete();
		}
		
		$this->_top->_sql->exeDummy("DELETE FROM ".TAB_PREF."page2content 
			WHERE page2content_id={$this->_content_id}");
		unset($this->_content_data);
	}
	
	private function update($param,$value)
	{
		if ($param=="content_id"  || $param=="content_type" || $param=="page_id") return false;
		
		$this->_data[$param] = $value;
		$value = $this->_top->Utils->prepareValueForSQL($value);
		$this->_top->_sql->exeDummy("UPDATE ".TAB_PREF."page2content SET $param='$value' 
			WHERE page2content_id={$this->_content_id}");
		return true;
	}
	
	
}

class PageTemplate {
	/**
	 * Pointer to self
	 *
	 * @var self
	 */
	private static $_instance;
	
	private static $_template_name;
	
	
	/**
	 * Pionter on class Template
	 *
	 * @var Template
	 */
	private $_template;
	
	/**
	 * Return current object instance
	 * @return PageTemplate
	 */
	public static function getInstance($template_name)
    {
    	self::$_template_name = $template_name;
    	
        if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
    
    public function __construct() {
    	$this->_template = MF_Main::getInstance()->Template;
    }
    
	public function getAttr($attr_name) {
		return $this->_template->getAttr(self::$_template_name,$attr_name);
	}
	
	public function getContentList() {
		return $this->_template->getContentList(self::$_template_name);
	}
	
	public function getStndContent($id) {
		return $this->_template->getStndContent($id);
	}
}
?>